<template>
  <div class="app-container inden-manage">
    <div>
      <avue-form
        :option="option"
        v-model="queryParams"
        ref="searchForm"
        @keydown.enter="getList"
      >
        <template #menu-form>
          <el-button icon="Search" type="primary" @click="getList" class="m-l-3"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleEmpty(searchForm)"
            >重置</el-button
          >
          <el-button icon="Download" @click="exportExcel('板块销售统计')"
            >导出</el-button
          >
        </template>
      </avue-form>

      <el-table
        ref="report-table"
        v-loading="loading"
        :data="tableList"
        row-key="id"
        stripe
        border
        :scrollbar-always-on="true"
        show-summary
      >
        <el-table-column
          type="index"
          width="60"
          label="序号"
          align="center"
          fixed="left"
        />
        <el-table-column
          label="单位"
          prop="name"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="(item, index) in tableCol"
          :key="index"
          :label="item.dictLabel"
          :prop="item.key"
          min-width="130"
        >
          <template #default="scope">
            <div v-if="scope.row[item.key] == 0">
              {{ scope.row[item.key] }}
            </div>
            <el-link
              v-else
              type="primary"
              :underline="false"
              @click="clickCell({ row: scope.row, col: item })"
              >{{ scope.row[item.key] }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column
          label="小计"
          prop="subtotal"
          width="130"
          align="center"
        ></el-table-column>
        <!-- <el-table-column
          label="操作"
          align="center"
          width="220"
          fixed="right"
          class-name="small-padding"
        >
          <template #header>
            <div>操作</div>
          </template>
          <template #default="scope">
            <el-button
              plain
              size="small"
              type="primary"
              icon="Postcard"
              v-loading="btnLoadingArr[scope.$index]"
              :disabled="
                scope.row.status == '4' ||
                scope.row.synchronousStatus !== '2' ||
                scope.row.approvalStatus !== '审批通过' ||
                scope.row.invoiceStatus == '1' ||
                scope.row.invoiceStatus == '3' ||
                btnLoadingArr[scope.$index]
              "
              v-hasPermi="['salesOrder:makeOutInvoice']"
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              @click="invoiceFn(scope.row, scope.$index)"
              >开票</el-button
            >
            <el-button
              plain
              size="small"
              type="primary"
              icon="Sort"
              :disabled="
                scope.row.invoiceStatus == '0' || scope.row.property == 1
              "
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              @click="reversalOrder(scope.row)"
              >冲红</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>

      <!-- <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      /> -->
    </div>

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    ></SelectDialog>

    <!-- 明细 -->
    <el-dialog title="销售明细" v-model="detailDia.open">
      <el-row :gutter="10" class="mb8">
        <el-col :span="24" class="text-right">
          <el-button icon="Download" @click="exportDetail('板块销售统计')"
            >导出</el-button
          >
        </el-col>
      </el-row>
      <el-table
        ref="report-table"
        v-loading="tableDetailLoading"
        :data="tableDetailList"
        row-key="id"
        stripe
        border
        :scrollbar-always-on="true"
        :cell-class-name="'cursor-pointer'"
        show-summary
        @row-dblclick="rowDblClick"
      >
        <el-table-column
          type="index"
          width="60"
          label="序号"
          align="center"
          fixed="left"
        />
        <el-table-column
          label="产品"
          prop="name"
          min-width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          label="规格型号"
          prop="specification"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          label="数量"
          prop="num"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          label="销售额"
          prop="price"
          width="100"
          align="center"
        ></el-table-column>
      </el-table>
      <pagination
        class="relative"
        v-show="detailTotal > 0"
        :total="detailTotal"
        v-model:page="detailParams.pageNum"
        v-model:limit="detailParams.pageSize"
        @pagination="getDetailList"
      />
    </el-dialog>
  </div>
</template>
<script setup name="PlateStatistics">
import { useRouter, useRoute } from 'vue-router'
import {
  businessTypeOption, //业务类型
  companyOption //所属公司
} from '@/hooks/dict/order'
import {
  statisticsBusiness,
  statisticsBusinessDetail
} from '@/api/orderStatistics/index'
import { treeselect } from '@/api/rsgl/zzjg'
import useCommonStore from '@/store/modules/common'
import { format, startOfMonth, endOfMonth } from 'date-fns'
import useUserStore from '@/store/modules/user'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'

const commonStore = useCommonStore()

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const userOption = ref({ userId: [] })
const deptIdOption = ref([])
const now = new Date()
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    startDate: undefined,
    endDate: undefined,
    // receiptsDates: [
    //   format(startOfMonth(now), 'yyyy-MM-dd'),
    //   format(endOfMonth(now), 'yyyy-MM-dd')
    // ],
    orgId: userStore.userInfo.orgId
  },
  total: 0,
  option: {
    labelWidth: '10',
    menuSpan: 6,
    submitBtn: false,
    menuPosition: 'left',
    // gutter: 30,
    emptyBtn: false,
    column: [
      {
        prop: 'startDate',
        type: 'date',
        span: 3,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '单据开始时间'
      },
      {
        prop: 'endDate',
        type: 'date',
        span: 3,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '单据结束时间'
      },
      {
        prop: 'orgId',
        span: 3,
        placeholder: '所属公司',
        type: 'tree',
        defaultExpandAll: true,
        disabled: userStore.userInfo.orgId != 484,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption,
        change: val => {
          queryParams.value.orgId = val.value
          getDeptTree()
        }
      },
      {
        prop: 'deptId',
        span: 3,
        placeholder: '所属部门',
        type: 'tree',
        defaultExpandAll: true,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: deptIdOption
      },
      {
        prop: '_userId',
        span: 3,
        placeholder: '所属人员',
        type: 'select',
        clearable: false,
        props: {
          value: 'uuid'
        },
        popperClass: 'className',
        dicData: computed(() => {
          return userOption.value['userId']
        }),
        multiple: false,
        click: ({ value, column }) => {
          dialogParam.value.type = 'userId'
          dialogParam.value.title = '请选择人员'
          dialogParam.value.isDialog = true
          dialogParam.value.multiple = false
          dialogParam.value.nodeKey = 'uuid'
          dialogParam.value.apiParams = { deptId: queryParams.value.orgId }
          dialogParam.value.defaultCheckedKeys = [queryParams.value._userId]
          dialogParam.value.dataType = 'person'
        }
      },
      {
        // label: '性别',
        span: 3,
        prop: 'businessType',
        placeholder: '业务分类',
        type: 'tree',
        multiple: true,
        checkStrictly: true,
        checkOnClickNode: true,
        dicData: businessTypeOption
      }
    ]
  },
  loading: false,
  tableList: [],
  dialogParam: {}
})
const { queryParams, total, option, loading, tableList, dialogParam } =
  toRefs(data)

const tableCol = ref([])
// 初始化
async function init() {
  // 归属部门
  getList()
}
// 获取部门树
const getDeptTree = () => {
  if (!queryParams.value.orgId) return
  queryParams.value.deptId = ''
  let data = { deptId: queryParams.value.orgId }
  treeselect(data).then(res => {
    deptIdOption.value = res.data
  })
}
getDeptTree()

// 重置
function handleEmpty(formEl) {
  proxy.resetForm('searchForm')
  getList()
}

// 获取数据列表
function getList() {
  loading.value = true
  statisticsBusiness(queryParams.value).then(res => {
    loading.value = false
    tableCol.value = res.data.label
    tableList.value = res.data.data
    // total.value = res.total
    console.log('res==>', res)
  })
  console.log('获取数据')
}

/* 人员确认 */
const selectDialogData = val => {
  switch (val.type) {
    case 'userId':
      userOption.value.userId = val.selectData
      // queryOption.value.column[2].dicData = val.selectData
      queryParams.value._userId = val.defaultCheckedKeys.toString()
      queryParams.value.userId = queryParams.value._userId.replace('U', '')
      break
  }
}

function goTo(url, data) {
  router.push({ path: url, query: data })
}
const detailDia = ref({
  open: false
})

// 详情参数
const detailParams = ref({})
const detailTotal = ref(0)
const tableDetailList = ref([])
const tableDetailLoading = ref(false)
const detailFileName = ref('')
// 点击单元格
const clickCell = ({ row, col }) => {
  detailParams.value = {
    startDate: queryParams.value.startDate,
    endDate: queryParams.value.endDate,
    orgId: queryParams.value.orgId,
    type: row.type,
    dictValue: col.dictValue,
    id: row.id,
    pageSize: 10,
    pageNum: 1
  }
  detailFileName.value = `${row.name}_${col.dictLabel}_${row.id}`
  detailDia.value.open = true
  getDetailList()
}
// 获取明细列表
const getDetailList = () => {
  tableDetailLoading.value = true
  statisticsBusinessDetail(detailParams.value).then(res => {
    tableDetailList.value = res.rows
    detailTotal.value = res.total
    tableDetailLoading.value = false
  })
}
// 导出明细
const exportDetail = () => {
  proxy.downLoadByUrl(
    '/ord/statistics/business/type/detail/export',
    detailParams.value,
    `板块统计明细_${detailFileName.value}.xlsx`
  )
}
// 前端导出excel
const exportExcel = excelName => {
  setTimeout(() => {
    try {
      const $e = proxy.$refs['report-table'].$el
      console.log(' $e==>', $e)
      let $table = $e.querySelector('.el-table__fixed')
      if (!$table) {
        $table = $e
      }

      const wb = XLSX.utils.table_to_book($table, { raw: true })
      const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      FileSaver.saveAs(
        new Blob([wbout], { type: 'application/octet-stream' }),
        `${excelName}.xlsx`
      )
    } catch (e) {
      if (typeof console !== 'undefined') console.error(e)
    }
  }, 500)
}
// 双击明细
const rowDblClick = row => {
  let data = {
    receiptsDates:
      queryParams.value.startDate && queryParams.value.endDate
        ? [queryParams.value.startDate, queryParams.value.endDate]
        : undefined,
    deptId: queryParams.value.orgId,
    productName: row.name,
    businessType: detailParams.value.dictValue
  }
  goTo('/sales/indent/salesOrder', {
    salesOrderData: JSON.stringify(data)
  })
}

init()
</script>
<style scoped>
.search-drawer-retract {
  color: #999999;
}
</style>
